var utils = {
    repage: function () {
        window.location.reload();
        return false;
    },
    back: function () {
        window.history.back(-1);
    },
    Urlhref: function (url) {
        window.location.href = url;
    },
    CheckAll: function (dom) {
        var obj = dom || '#grid';
        $(obj + " :checkbox").prop("checked", true);
    },
    CheckOther: function (dom) {
        var obj = dom || '#grid';
        $(obj + " :checkbox").each(function () {
            $(this).prop("checked", !$(this).prop("checked"));
        });
    },
    CheckboxValue: function (dom) {
        var obj = dom || '#grid';
        var reVal = '';
        $(obj).find("input[type='checkbox']").each(function () {
            if ($(this).prop("checked")) {
                reVal += $(this).val() + ",";
            }
        });
        reVal = reVal.substr(0, reVal.length - 1);
        return reVal;
    },
    checkOne: function (reVal) {
        var that = this;
        var flag = true;
        if (reVal == undefined || reVal == "") {
            that.error('请选择要操作的数据');
            flag = false;
        } else if (reVal.split(",").length > 1) {
            that.error('对不起，只能选择一条数据');
            flag = false;
        }
        return flag;
    },
    checkMore: function (reVal) {
        var flag = true;
        if (reVal == undefined || reVal == "") {
            that.error('请选择要操作的数据');
            flag = false;
        }
        return flag;
    },
    jsonCol: function (json, col) {
        var len = json.length;
        if (len == 0) {
            return false;
        } else {
            var reval = [];
            for (var i = 0; i < len; i++) {
                reval.push(json[i][col]);
            }
            return reval.join(',');
        }
    },
    loading: function (msg) {
        var loadingText = msg || '数据加载中……';
        $.showLoading(loadingText);
    },
    hideLoading: function () {
        $.hideLoading();
    },
    //success error warning;
    toptip:function(msg,duration,type){
        $.toptip(msg, duration, type);
    },
    tips: function (msg) {
        $.toast(msg, "text");
    },
    error: function (msg, callfn) {
        $.toast(msg, "cancel", callfn);
    },
    success: function (msg, callfn) {
        $.toast(msg, callfn);
    },
    confirm: function (msg, onOK, onCancel) {
        $.confirm(msg, "提示消息", onOK, onCancel);
    },
    openDialog: function (options) {
        var defaultConfig = {
            type: 1, //0表示信息框，1表示页面层，2表示加载层
            skin: 'footer' //目前支持配置 footer（即底部对话框风格）、msg（普通提示） 两种风格。
        };
        var config = $.extend({}, defaultConfig, options);
        In('layer', function () {
            layer.open(config);
        });
    },
    openfull: function (html, callfn) {
        In('layer', function () {
            layer.open({
                type: 1,
                content: html,
                anim: false,
                style: 'position:fixed; left:0; top:0; width:100%; height:100%; border: none; -webkit-animation-duration: .5s; animation-duration: .5s;',
                success: function (elem) {
                    callfn(elem);
                }
            });
        });
    },
    closeLayer: function () {
        In('layer', function () {
            layer.closeAll();
        });
    },
    getAjax: function (options) {
        var that = this;
        var defaultConfig = {
            type: 'post',
            cache: true,
            async: true,
            dataType: 'json',
            // beforeSend: function () {
            //     that.loading();
            // },
            error: function () {
                that.error('与服务器断开连接');
                return false;
            },
            // complete: function () {
            //     that.hideLoading();
            // }
        };
        var config = $.extend({}, defaultConfig, options);
        $.ajax(config);
    },
    doConfirm: function (msg, options) {
        var that = this;
        that.confirm(msg, function () {
            that.getAjax(options);
        });
    },
    doAction: function (obj, callfn) {
        var that = this;
        var msg = $(obj).data('msg');
        var url = $(obj).data('url');
        var params = $(obj).data('params');
        this.doConfirm(msg, {
            url: url,
            data: params,
            success: function (res) {
                if (res.code == 1) {
                    if (typeof(callfn) == "undefined") {
                        that.Urlhref(res.url);
                    } else if (callfn == 'repage') {
                        that.repage();
                    } else {
                        callfn(res);
                    }
                } else {
                    that.error(res.msg);
                }
            }
        });
    },
    ajaxSubForm: function (options, dom) {
        var obj = dom || '#form';
        var that = this;
        var defaultConfig = {
            ajaxPost: true,
            postonce: true,
            tipSweep: true,
            tiptype: function (msg, o, cssctl) {
                if (o.type == 3) {
                    that.toptip(msg,'warning');
                }
                return false;
            },
            beforeSubmit: function (curform) { //表单验证通过

            },
            callback: function (res) {
                if (res.code == 1) {
                    that.Urlhref(res.url);
                } else {
                    that.toptip(res.msg,'warning');
                }
                return false;
            }
        };
        var config = $.extend({}, defaultConfig, options);
        In('validform', function () {
            $(obj).Validform(config);
        })
    },
    dateDiff: function (timestamp) {
        // 补全为13位
        var arrTimestamp = (timestamp + '').split('');
        for (var start = 0; start < 13; start++) {
            if (!arrTimestamp[start]) {
                arrTimestamp[start] = '0';
            }
        }
        timestamp = arrTimestamp.join('') * 1;

        var minute = 1000 * 60;
        var hour = minute * 60;
        var day = hour * 24;
        var halfamonth = day * 15;
        var month = day * 30;
        var now = new Date().getTime();
        var diffValue = now - timestamp;

        // 如果本地时间反而小于变量时间
        if (diffValue < 0) {
            return '不久前';
        }

        // 计算差异时间的量级
        var monthC = diffValue / month;
        var weekC = diffValue / (7 * day);
        var dayC = diffValue / day;
        var hourC = diffValue / hour;
        var minC = diffValue / minute;

        // 数值补0方法
        var zero = function (value) {
            if (value < 10) {
                return '0' + value;
            }
            return value;
        };

        // 使用
        if (monthC > 12) {
            // 超过1年，直接显示年月日
            return (function () {
                var date = new Date(timestamp);
                return date.getFullYear() + '年' + zero(date.getMonth() + 1) + '月' + zero(date.getDate()) + '日';
            })();
        } else if (monthC >= 1) {
            return parseInt(monthC) + "月前";
        } else if (weekC >= 1) {
            return parseInt(weekC) + "周前";
        } else if (dayC >= 1) {
            return parseInt(dayC) + "天前";
        } else if (hourC >= 1) {
            return parseInt(hourC) + "小时前";
        } else if (minC >= 1) {
            return parseInt(minC) + "分钟前";
        }
        return '刚刚';
    },
    dateFormat: function (timestamp, formats) {
        // formats格式包括
        // 1. Y-m-d
        // 2. Y-m-d H:i:s
        // 3. Y年m月d日
        // 4. Y年m月d日 H时i分
        formats = formats || 'Y-m-d';

        var zero = function (value) {
            if (value < 10) {
                return '0' + value;
            }
            return value;
        };
        timestamp = timestamp * 1000;
        var myDate = timestamp ? new Date(timestamp) : new Date();

        var year = myDate.getFullYear();
        var month = zero(myDate.getMonth() + 1);
        var day = zero(myDate.getDate());

        var hour = zero(myDate.getHours());
        var minite = zero(myDate.getMinutes());
        var second = zero(myDate.getSeconds());

        return formats.replace(/Y|m|d|H|i|s/ig, function (matches) {
            return ({
                Y: year,
                m: month,
                d: day,
                H: hour,
                i: minite,
                s: second
            })[matches];
        });
    },
    uploadOnePic: function (obj, options, callback, beforeCallback) {
        var that = this;
        var uploader_obj = 'uploader_' + obj;
        var server = '/plus/uploader/index.html?action=uploadimage';
        var defaultConfig = {
            auto: true,
            resize: true,
            duplicate: true,
            swf: '/static/plugins/webuploader/Uploader.swf',
            server: server,
            pick: "#" + obj,
            fileVal: 'upfile',
            accept: {
                title: 'Images',
                extensions: 'gif,jpg,jpeg,bmp,png',
                mimeTypes: 'image/gif,image/jpeg,image/jpg,image/png,image/svg'
            },
            compress: {width: 800, height: 1600, quality: 80, compressSize: 204800}
        };
        var config = $.extend({}, defaultConfig, options);
        In.use('webuploader', function () {
            uploader_obj = WebUploader.create(config);
            // 当有文件被添加进队列的时候
            uploader_obj.on('beforeFileQueued', function (file) {
                if (typeof(beforeCallback) == "undefined") {
                    return true;
                } else {
                    return beforeCallback(file);
                }
            });
            uploader_obj.on('uploadSuccess', function (file, response) {
                if (response.state == 'SUCCESS') {
                    callback(response);
                } else {
                    that.error(response.state);
                }
            });
        })
    },
    uploadOneFile: function (obj, options, callback, beforeCallback) {
        var that = this;
        var uploader_obj = 'uploader_' + obj;
        var server = '/plus/uploader/index.html?action=uploadfile';
        var defaultConfig = {
            auto: true,
            resize: true,
            duplicate: true,
            swf: '/static/plugins/webuploader/Uploader.swf',
            server: server,
            pick: "#" + obj,
            fileVal: 'upfile'
        };
        var config = $.extend({}, defaultConfig, options);
        In.use('webuploader', function () {
            uploader_obj = WebUploader.create(config);
            // 当有文件被添加进队列的时候
            uploader_obj.on('beforeFileQueued', function (file) {
                if (typeof(beforeCallback) == "undefined") {
                    return true;
                } else {
                    return beforeCallback(file);
                }
            });
            uploader_obj.on('uploadSuccess', function (file, response) {
                if (response.state == 'SUCCESS') {
                    callback(response);
                } else {
                    that.error(response.state);
                }
            });
        })
    },
    initPage: function (dom, options) {
        var defaultConfig = {
            page: {num: 1, size: 10},
            auto: true,//初始化完毕,是否自动触发上拉加载的回调
            isBoth: false, //上拉加载时,如果滑动到列表顶部是否可以同时触发下拉刷新;默认false,两者不可同时触发; 这里为了演示改为true,不必等列表加载完毕才可下拉;
            isBounce: false, //此处禁止ios回弹,解析(务必认真阅读,特别是最后一点): http://www.mescroll.com/qa.html#q10
            clearEmptyId: dom,
            noMoreSize: 6,
            offset: 100,
            //htmlNodata: '<p class="upwarp-nodata">-- END -- </p>',
            htmlNodata: '',
            toTop: { //配置回到顶部按钮
                src: "/static/plugins/mescroll/mescroll-totop.png" //默认滚动到1000px显示,可配置offset修改
            }
        };
        var upconfig = $.extend({}, defaultConfig, options);
        In('mescroll', function () {
            new MeScroll("mescroll", {
                down:{
                    auto: true,
                    isBoth: false, //上拉加载时,如果滑动到列表顶部是否可以同时触发下拉刷新;默认false,两者不可同时触发; 这里为了演示改为true,不必等列表加载完毕才可下拉;
                    isBounce: false, //此处禁止ios回弹,解析(务必认真阅读,特别是最后一点): http://www.mescroll.com/qa.html#q10
                    hardwareClass:"mescroll-hardware"
                },
                up: upconfig
            });
        });
    },
    initPage2:function (options,dom) {
        var obj = dom || '#page';
        var params = options.params || {};
        In('paginationjs','layer','template',function () {
            var defaultConfig = {
                locator:'rows',
                totalNumberLocator:function (response) {
                    return response.total;
                },
                className:'paginationjs-theme-blue',
                pageSize: 12,
                prevText:'上一页',
                nextText:'下一页',
                ajax: {
                    type:'post',
                    data:params,
                    beforeSend: function() {
                        layer.open({type: 2});
                    },
                    complete:function () {
                        layer.closeAll();
                    }
                }
            };
            var config = $.extend({}, defaultConfig, options);
            $(obj).pagination(config);
        });
    },
    getQueryString: function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    },
    //生成二维码
    Qrcode: function (obj, options) {
        var defaultConfig = {
            width: 128,
            height: 128,
            colorDark: "#000000",
            colorLight: "#ffffff",
            correctLevel: QRCode.CorrectLevel.H
        };
        var config = $.extend({}, defaultConfig, options);
        In('qrcode', function () {
            var qrcode = new QRCode(document.getElementById(obj), config);
            return qrcode;
        });
    },
    //输入文本统计输入字符数
    wordStatic:function (input,dom) {
        //alert(123);
    // 获取要显示已经输入字数文本框对象
        var obj = dom || '#word_num';
        if (obj && input) {
            // 获取输入框输入内容长度并更新到界面
            var value = input.value;
            // 将换行符不计算为单词数
            value = value.replace(/\n|\r/gi,"");
            // 更新计数
            $(obj).text(value.length);
        }
    },
/*格式化成带,号的金融计数*/
    formatNum: function (str) {
        var newStr = "";
        var count = 0;
        if (str.indexOf(".") == -1) {
            for (var i = str.length - 1; i >= 0; i--) {
                if (count % 3 == 0 && count != 0) {
                    newStr = str.charAt(i) + "," + newStr;
                } else {
                    newStr = str.charAt(i) + newStr;
                }
                count++;
            }
            str = newStr + ".00"; //自动补小数点后两位
        } else {
            for (var i = str.indexOf(".") - 1; i >= 0; i--) {
                if (count % 3 == 0 && count != 0) {
                    newStr = str.charAt(i) + "," + newStr;
                } else {
                    newStr = str.charAt(i) + newStr; //逐个字符相接起来
                }
                count++;
            }
            str = newStr + (str + "00").substr((str + "00").indexOf("."), 3);
        }
        return str;
    },
    /*===================================================================================*/
    /*====  apicloud接口方法  ============================================================*/
    /*===================================================================================*/
    /*打开新窗口*/
    openpage:function (name,url) {
        api.openWin({
            name:name,
            url:url,
            bounces: false,
            rect: {
                x: 0,
                y: 0,
                w: 'auto',
                h: 'auto'
            }
        });
    },
    /*关闭窗口*/
    closepage:function () {
        api.closeWin();
    }
};